<template>
  <div>
    <el-form
      ref="form"
      :rules="rules"
      style="padding-top: 10px"
      :model="form"
      label-width="100px"
    >
      <div class="com-form-title">基础信息</div>
      <el-row>
        <el-col :span="8">
          <el-form-item label="单据编号" prop="number">
            <el-input
              v-model="form.number"
              :disabled="true"
              placeholder="自动生成"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="部门名称" prop="departmentName">
            <el-input v-model="form.departmentName" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请支付" prop="applyPayment">
            <el-input v-model="form.applyPayment" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="批复金额" prop="approvedAmount">
            <el-input v-model="form.approvedAmount" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结算金额" prop="settleAmount">
            <el-input v-model="form.settleAmount" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="已支付金额" prop="paidAmount">
            <el-input v-model="form.paidAmount" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发票金额" prop="invoiceAmount">
            <el-input v-model="form.invoiceAmount" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="描述" prop="description">
            <el-input v-model="form.description" :disabled="disableForm" />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="btns" style="padding-bottom: 10px">
        <el-button type="primary" :disabled="disableForm" @click="addRow">新增行</el-button>
        <el-button type="primary" :disabled="disableForm" @click="delDetailDataItem">删除行</el-button>
      </div>
      <com-table
        v-model="selectRow"
        :no-page="true"
        :columns="columns"
        highlight-current-row
        :data="detailDataList"
      >
        <template v-slot:sequence="{ row }">
          <el-input v-model="row.sequence" :disabled="disableForm" />
        </template>
        <template v-slot:fundUse="{ row }">
          <el-select
            v-model="row.fundUse"
            :disabled="disableForm"
            style="width: 100%"
            placeholder="请选择资金用途"
          >
            <el-option
              v-for="item in paymentFundUse"
              :key="item.name"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </template>
        <template v-slot:accountSubjects="{ row }">
          <el-select
            v-model="row.accountSubjects"
            :disabled="disableForm"
            style="width: 100%"
            placeholder="请选择会计科目"
          >
            <el-option
              v-for="item in paymentAccountSubjects"
              :key="item.name"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </template>
        <template v-slot:contractNumber="{ row }">
          <el-input
            v-model="row.contractNumber"
            :disabled="disableForm"
            @click.native="optType === 'add' ? (showListModal = true) : null"
          >>
            <i
              slot="suffix"
              class="el-input__icon el-icon-circle-plus-outline"
            />
          </el-input>
        </template>
        <template v-slot:contractAmount="{ row }">
          <el-input v-model="row.contractAmount" :disabled="disableForm" />
        </template>
        <template v-slot:unitName="{ row }">
          <el-input v-model="row.unitName" :disabled="disableForm" />
        </template>
        <template v-slot:thisSettleAmount="{ row }">
          <el-input v-model="row.thisSettleAmount" :disabled="disableForm" @focus="sumSettleAmount" />
        </template>
        <template v-slot:cumulativeSettleAmount="{ row }">
          <el-input v-model="row.cumulativeSettleAmount" :disabled="disableForm" />
        </template>
        <template v-slot:thisInvoiceAmount="{ row }">
          <el-input v-model="row.thisInvoiceAmount" :disabled="disableForm" @focus="sumInvoiceAmount" />
        </template>
        <template v-slot:cumulativeInvoiceAmount="{ row }">
          <el-input v-model="row.cumulativeInvoiceAmount" :disabled="disableForm" />
        </template>
        <template v-slot:thisApplyPayment="{ row }">
          <el-input v-model="row.thisApplyPayment" :disabled="disableForm" @input="sumPayment" />
        </template>
        <template v-slot:remark="{ row }">
          <el-input v-model="row.remark" :disabled="disableForm" />
        </template>
        <template v-slot:lstAttachment="{ row }">
          <a
            class="com-link"
            @click="uploaderFielRow(row)"
          >文件数（{{ row.lstAttachment.length }}）</a>
        </template>
      </com-table>
      <!-- <el-button style="margin-top:10px;" type="primary" @click="showFileModal = true">附件资料({{ fileList.length }})</el-button> -->
      <file-uploader
        v-model="fileList"
        :show-modal.sync="showFileModal"
        :disabled="disableForm"
        :can-download="optType === 'detail'"
      />
    </el-form>
    <div style="visibility:hidden; height: 20px;" />
    <span slot="footer" class="dialog-footer">
      <el-button v-show="displayBtn" type="primary" @click="saveDoc">确 定</el-button>
    </span>
    <ContractList1
      :show-modal.sync="showListModal"
      title="合同编号列表"
      :columns="listColumns"
      :api="getBankExternalContractInfoList"
      @getSelectedData="getSelectedRows"
    />
  </div>
</template>

<script>
import { getBankExternalContractInfoList } from '@/api/bigManage'
import {
  getBankExternalPaymentInfoDetail,
  updateBankExternalPaymentApprovedAmount
} from '@/api/runMoneyManage'
import { getNextWorkflow } from '@/api/flow'
import { getAreaList } from '@/api/common'
import ContractList1 from '@/components/ContractList1'

import {
  paymentFundUse,
  paymentAccountSubjects,
  workflowStatus
} from '@/utils/dicData'
import fileUploader from '@/components/FileUploader'
export default {
  name: 'AddBankExternalPaymentInfo',
  components: {
    fileUploader,
    ContractList1
  },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      displayBtn: false,
      getBankExternalContractInfoList,
      showFileModal: false,
      targetList: [],
      paymentFundUse,
      paymentAccountSubjects,
      workflowStatus,
      showListModal: false,
      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        number: '',
        departmentName: '',
        applyPayment: '',
        approvedAmount: '',
        settleAmount: '',
        paidAmount: '',
        invoiceAmount: '',
        description: '',
        addWorkflowId: '',
        status: '',
        founderName: '',
        createTime: ''
      },
      showAddDetailModal: false,
      selectRow: null,
      detailDataList: [],
      detailDataItem: {},
      listColumns: [
        {
          label: '合同编号',
          prop: 'contractNumber'
        },
        {
          label: '合同名称',
          prop: 'contractName'
        },
        {
          label: '合同金额',
          prop: 'contractAmount'
        },
        {
          label: '合同单位名称',
          prop: 'contractUnitName'
        }
      ],
      columns: [
        {
          label: '序号',
          slot: 'sequence'
        },
        {
          label: '资金用途',
          slot: 'fundUse',
          width: '130'
        },
        {
          label: '会计科目',
          slot: 'accountSubjects',
          width: '120'
        },
        {
          label: '合同编号',
          slot: 'contractNumber',
          width: '200'
        },
        {
          label: '合同金额',
          slot: 'contractAmount',
          width: '150'
        },
        {
          label: '单位名称',
          slot: 'unitName',
          width: '150'
        },
        {
          label: '本次结算金额',
          slot: 'thisSettleAmount',
          width: '150'
        },
        {
          label: '累计结算金额',
          slot: 'cumulativeSettleAmount',
          width: '150'
        },
        {
          label: '本次发票金额',
          slot: 'thisInvoiceAmount',
          width: '150'
        },
        {
          label: '累计发票金额',
          slot: 'cumulativeInvoiceAmount',
          width: '150'
        },
        {
          label: '本次申请支付',
          slot: 'thisApplyPayment',
          width: '150'
        },
        {
          label: '备注',
          slot: 'remark',
          width: '150'
        },
        {
          label: '附件',
          slot: 'lstAttachment',
          width: '150'
        }
      ],
      showTargetSetListModal: false,
      fileList: [],
      rules: {
        departmentName: [
          { required: true, message: '请输入项目名称', trigger: 'change' }
        ],
        approvedAmount: [
          { required: true, message: '请输入批复金额', trigger: 'change' }
        ]
      },
      detailRules: {
        sequence: [
          { required: true, message: '请输入序号', trigger: 'change' }
        ],
        contractNumber: [
          { required: true, message: '请输入合同编号', trigger: 'change' }
        ],
        contractAmount: [
          { required: true, message: '请输入合同金额', trigger: 'change' }
        ],
        unitName: [
          { required: true, message: '请输入单位名称', trigger: 'change' }
        ],
        thisSettleAmount: [
          { required: true, message: '请输入本次结算金额', trigger: 'change' }
        ],
        cumulativeSettleAmount: [
          { required: true, message: '请输入累计结算金额', trigger: 'change' }
        ],
        thisInvoiceAmount: [
          { required: true, message: '请输入本次发票金额', trigger: 'change' }
        ],
        cumulativeInvoiceAmount: [
          { required: true, message: '请输入累计发票金额', trigger: 'change' }
        ],
        thisApplyPayment: [
          { required: true, message: '请输入本次申请支付', trigger: 'change' }
        ]
      },
      provinceData: [],
      cityData: []
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
      }
    }
  },
  watch: {
    fileList(val) {
      if (this.uploadRow) {
        this.uploadRow.lstAttachment = val
      }
    },
    showFileModal(val) {
      if (!val) {
        this.uploadRow = null
      }
    },
    data: {
      handler(newData, oldData) {
        if (newData.businessId) {
          this.getDocDetail(newData.businessId)
          const { id } = this.data
          if (!id) return
          const params = {
            startWorkflowId: id
          }
          getNextWorkflow(params).then(res => {
            const { code } = res
            if (code !== '0001') {
              this.displayBtn = true
            } else {
              this.displayBtn = false
            }
          })
        }
      },
      immediate: true
    }
  },
  mounted() {
    // this.getRegionData()
  },
  methods: {
    sumPayment() {
      this.form.applyPayment = 0
      this.detailDataList.forEach(item => {
        this.form.applyPayment = this.form.applyPayment * 1 + item.thisApplyPayment * 1
      })
      this.$forceUpdate()
    },
    sumSettleAmount() {
      this.form.settleAmount = 0
      this.detailDataList.forEach(item => {
        this.form.settleAmount = this.form.settleAmount * 1 + item.thisSettleAmount * 1
      })
      this.$forceUpdate()
    },
    sumInvoiceAmount() {
      this.form.invoiceAmount = 0
      this.detailDataList.forEach(item => {
        this.form.invoiceAmount = this.form.invoiceAmount * 1 + item.thisInvoiceAmount * 1
      })
      this.$forceUpdate()
    },
    addRow() {
      this.detailDataList = [
        ...this.detailDataList,
        {
          sequence: '',
          fundUse: '',
          accountSubjects: '',
          contractNumber: '',
          contractAmount: '',
          unitName: '',
          thisSettleAmount: '',
          cumulativeSettleAmount: '',
          thisInvoiceAmount: '',
          cumulativeInvoiceAmount: '',
          thisApplyPayment: '',
          remark: '',
          lstAttachment: []
        }
      ]
      this.detailDataList.forEach((element, index) => {
        element.sequence = index + 1
      })
    },
    getSelectedRows(data) {
      if (data) {
        this.selectRow.contractNumber = data.contractNumber
        this.selectRow.contractAmount = data.contractAmount
        this.selectRow.unitName = data.contractUnitName
      }
    },
    uploaderFielRow(row) {
      this.uploadRow = row
      this.fileList = row.lstAttachment
      this.showFileModal = true
    },
    addDetail() {
      this.$refs.detailForm.validate((valid) => {
        if (valid) {
          const item = JSON.parse(JSON.stringify(this.detailDataItem))
          this.detailDataList.push({
            ...item,
            lstAttachment: []
          })
          this.showAddDetailModal = false
          this.$refs.detailForm.resetFields()
        }
      })
    },
    cancelAddDetail() {
      this.showAddDetailModal = false
    },
    delDetailDataItem() {
      if (this.selectRow) {
        const index = this.detailDataList.indexOf(this.selectRow)
        this.detailDataList.splice(index, 1)
      }
    },
    provinceChange(e) {
      const selectedData = this.provinceData.filter((val) => val.name === e)[0]
      if (selectedData) {
        this.form.city = ''
        const params = {
          parentCode: selectedData.code,
          areaType: 2
        }
        getAreaList(params).then((res) => {
          this.cityData = res.data || []
        })
      }
    },
    getDocDetail(id) {
      getBankExternalPaymentInfoDetail({ bankExternalPaymentInfoId: id }).then(
        (res) => {
          const { lstBankExternalPaymentDetail, bankExternalPaymentInfo } =
            res.data || {}
          if (
            lstBankExternalPaymentDetail &&
            lstBankExternalPaymentDetail.length > 0
          ) {
            this.detailDataList = lstBankExternalPaymentDetail.map((item) => {
              return {
                ...item.bankExternalPaymentDetail,
                lstAttachment: item.lstAttachment
              }
            })
            this.detailDataList.forEach(item => {
              item.fundUse = item.fundUse * 1
            })
          }
          Object.keys(this.form).forEach((key) => {
            this.form[key] = bankExternalPaymentInfo[key]
          })
        }
      )
    },
    getRegionData() {
      getAreaList({ areaType: '1' }).then((res) => {
        this.provinceData = res.data || []
      })
    },
    deleteDetail() {},
    saveDoc() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {
            bankExternalPaymentInfoId: this.data.businessId,
            approvedAmount: this.form.approvedAmount
          }
          updateBankExternalPaymentApprovedAmount(params).then(res => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.com-form-title{
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409EFF;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}
::v-deep .el-form-item__label{
  color: #000;
}
::v-deep .el-input.is-disabled .el-input__inner{
  color: #000;
}
::v-deep .el-input.is-disabled .el-input__inner{
  color: #000;

}
.dialog-footer {
  padding-left: 45%;
}
</style>
